package cn.apelx.order.controller;

import cn.apelx.api.store.service.StoreDubboService;
import cn.apelx.order.domain.Orders;
import cn.apelx.order.repository.OrdersRepository;
import cn.apelx.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * 订单controller
 *
 * @author apelx
 * @since 2022-05-01
 */
@RestController
@RequestMapping(value = "/order")
public class OrdersController {

    @DubboReference
    private StoreDubboService storeDubboService;

    @Autowired
    private OrdersRepository ordersRepository;

    @Autowired
    private OrderService orderService;
    /**
     * 下单操作
     *
     * @return
     */
    @GlobalTransactional(rollbackFor = {Exception.class})
    @GetMapping(value = "/create/{name}/{price}")
    public String create(@PathVariable String name, @PathVariable BigDecimal price) {

        Orders orders = new Orders("订单" + name, price);
        ordersRepository.save(orders);

        String storeId = "store-id-001";

        storeDubboService.subStore(storeId, new BigDecimal("1"));

        System.out.println(10 / 0);
        return "success";
    }


    /**
     * 下单操作
     * 库存走数据库的同时，还往redis插入数据
     *
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @GetMapping(value = "/createTcc/{name}/{price}")
    public String createTcc(@PathVariable String name, @PathVariable BigDecimal price) {

        orderService.createTcc(null, name, price);
        return "success";
    }

    /**
     * 测试调用链路
     * @return
     */
    @GetMapping(value = "/get")
    public String get(){
        return "订单xxx" + storeDubboService.getStore();
    }
}
